package com.cxlin.base.ext

import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/25 14:21
 */

inline fun <reified VB : ViewDataBinding> Fragment.binding() =
    FragmentBindingProperty(VB::class.java)


class FragmentBindingProperty<VB : ViewDataBinding>(private val clazz: Class<VB>) :
    ReadOnlyProperty<Fragment, VB> {
    private var binding: VB? = null
    private val handler by lazy { Handler(Looper.getMainLooper()) }

    override fun getValue(thisRef: Fragment, property: KProperty<*>): VB {
        if (binding == null) {
            try {
                binding = (clazz.getMethod("bind", View::class.java)
                    .invoke(null, thisRef.requireView()) as VB)
                    .apply {
                        lifecycleOwner = thisRef.viewLifecycleOwner
                    }
            } catch (e: IllegalStateException) {
                throw IllegalStateException("The property of ${property.name} has been destroyed.")
            }
            thisRef.viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    handler.post { binding = null }
                }
            })
        }
        return binding!!
    }

}

inline fun <reified T:Fragment> T.newInstance(data: Bundle? = null):T{
    val fragment = T::class.constructors.first().call()
    data?.run {
        fragment.arguments = data
    }
    return fragment
}